// 云函数入口文件
const cloud = require('wx-server-sdk')

cloud.init()

const db = cloud.database();
const col = db.collection('two');
const _ = db.command;




// 云函数入口函数
exports.main = async (event, context) => {
  const wxContext = cloud.getWXContext()

// 查询数据
let user =await col.where({
  '_openid': wxContext.OPENID
}).get();
user = user.data[0];

if(user.prize !==null){
  //  return {
  //     msg:'你抽过奖啦！',
  //   success:false
  //  }
  
// }else{
  let rand = Math.random();
  let prize;
  switch (true) {
    case (rand < 0.1):
      prize = 1;
      break;
    case (rand >= 0.1 && rand < 0.3):
      prize = 2;
      break;
    case(rand>=0.3&&rand<0.6):
      prize=3;
      break;
    case (rand >= 0.6):
      prize = 0;
      break;
  }

  let zero = event.selectedArr[0]
  let one = event.selectedArr[1]

  // 选中的邮卡数量-1
  user.words[zero].number -= 1;
  user.words[one].number -= 1;

  // 待执行更新后再渲染前端
  await col.where({
    '_openid': wxContext.OPENID
  }).update({
    data: {
      prize: prize,
      words: user.words
    }
  });

  return {
    prize: prize,
    success: true,
    words: user.words
  }
}

}